<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Storage;
use Ramsey\Uuid\Uuid;

class FileController extends Controller
{
    /**
     * 上传单个文件
     * @return string
     */
    public function upload(Request $request){
        $callback = Input::get('callback');
        $files = $request->allFiles();
        if(count($files) < 1){
            return self::apiFail('文件不存在');
        }
        foreach($files as $key =>$file){
            if(empty($file)){
                return self::apiFail('文件不存在');
            }
            if (!$file->isValid()) {
                return self::apiFail('文件上传失败');
            }
            if (!$this->checkFileType($file->getClientOriginalExtension())) {
                return self::apiFail('不支持该文件格式');
            }
            if ($file->getSize() / 1024 / 1024 > 10) {
                return self::apiFail('文件大小不能超过10M');
            }
            $path = '/storage/' . Storage::disk('public')->putFileAs(rand(1,999), $file, md5(Uuid::uuid4()).'.'.$file->getClientOriginalExtension());
            return self::apiSucc(['path' => $path,'filename' => $file->getClientOriginalName(),'name'=>$key],$callback);
        }
        return self::apiSucc();
    }

    private function checkFileType($extension){
        $fileTypes = array('mov', 'zip','rar','mp3','mp4','pdf','doc','docx','csv','xls','xlsx','ppt','pptx','png','jpg','jpeg','txt');
        return in_array(strtolower($extension),$fileTypes);
    }

    public function getFile($id,$fileName){
        echo $id.$fileName;
    }
}
